package com.xh3140.xwidget.imageview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import java.io.IOException;

public class WiderImageView extends AppCompatImageView {
  public WiderImageView(@NonNull Context context) {
    this(context, null);
  }

  public WiderImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public WiderImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.WiderImageView, 0, 0);
    try {
      if (a.hasValue(R.styleable.WiderImageView_assetName)) {
        setImageAssetName(a.getString(R.styleable.WiderImageView_assetName));
      }
    } finally {
      a.recycle();
    }
  }

  public void setImageAssetName(@NonNull String assetName) {
    try {
      setImageBitmap(BitmapFactory.decodeStream(getContext().getAssets().open(assetName)));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
